import ScrollViewToolParent from "./ScrollViewToolParent";

const { ccclass, property, menu, disallowMultiple } = cc._decorator;
/** 
 * 分页查询,scroolView 辅助工具类
 */
@ccclass
@menu("自定义组件/ScrollView/分页查询")
@disallowMultiple
export default class PagingQueryScrollView extends ScrollViewToolParent {
    /** 总数据 */
    _totalDataCount = 999999999

    /** API接口
     * 
     * @param dataCount 当前数据长度
     * @param callback 子节点赋值回调
     * @param continueQueryCallback 继续查询回调
     * @param totalDataCount 总数据量
     * @param itemIsInit 节点使用时是否执行了数据初始化
     */
    setData(
        dataCount: number,
        callback: (node: cc.Node, index: number, isDynamic: boolean) => void,
        continueQueryCallback: (index: number, /** 查询完毕后刷新数据个数回调*/refreshDataCountCallback: (dataCount: number) => void) => void,
        totalDataCount: number,
        itemIsInit: boolean = false
    ) {
        this._initAllItem()
        if (dataCount == 0) {
            return
        }
        this._callback = callback
        this._continueQueryCallback = continueQueryCallback;
        this._dataCount = dataCount
        this._itemIsInitByCallBack = itemIsInit
        this._totalDataCount = totalDataCount || this._totalDataCount


        this.scrollview.stopAutoScroll()

        this._refreshUnUseChildData(true)
        this._content.y = 0;
    }


    /** 获取新的数据
     * 
     * @param index 当前index值
     */
    _getNewData(index, isTop = false) {
        cc.log("獲取新的數據 children")

        if (this._continueQueryCallback) {
            //到最后一个数据 &&  没有在查询 && 当前获得的数据小于总的数据
            if (index >= this._dataCount - 1 && !this._notQuerying && this._dataCount < this._totalDataCount) {
                this._notQuerying = true
                this._continueQueryCallback(this._dataCount, this._refreshDataCount.bind(this))
            }
        }
    }
    /** 刷新数据个数 */
    _refreshDataCount(dataCount) {
        //如果这次请求的数据和之前的数据数量相同,则没有更多的数据了
        if (dataCount == this._dataCount) {
            this._totalDataCount = dataCount
        }
        this._notQuerying = false
        this._dataCount = dataCount
        this._refreshUnUseChildData(false)
    }


}
